package com.jch.netty_client;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;

public class NettyDemoClient {

    public static void main(String[] args) {
        new NettyDemoClient().connect("127.0.0.1",1117);
    }

    private void connect(String host, int port) {
        // 客户端只有一个线程组，获取连接和处理事件
        EventLoopGroup worker = new NioEventLoopGroup();
        try {
            Bootstrap b = new Bootstrap();
            b.group(worker)
                    .channel(NioSocketChannel.class) // 使用NioSocketChannel
                    .option(ChannelOption.AUTO_READ,true) // 自动读取
                    .handler(new DemoChannelInitializer());
            ChannelFuture cf = b.connect(host,port).sync(); // 异步连接服务器
            System.out.println("Netty demo client start");
            cf.channel().closeFuture().sync(); // 监听关闭
        } catch (InterruptedException e) {
            e.printStackTrace();
        }finally {
            worker.shutdownGracefully();
        }
    }
}
